<?php

!defined('IN_APP') && exit('Access Denied');

class base {

    var $ip;
    var $time;
    var $db;
    var $cache;
    var $user = array();
    var $setting = array();
    var $category = array();
    var $nav = array();
    var $usergroup = array();
    var $get = array();
    var $post = array();
    var $regular; //当前访问的规则，例如 category/view
    var $statusarray = array('all' => '全部', '0' => '待审核', '1' => '待解决', '2' => '已解决', '4' => '悬赏', '9' => '已关闭');

    function __construct(& $get, & $post) {
        $this->time = time();
        $this->ip = getip();
        $this->get = & $get;
        $this->post = & $post;
        $this->init_db();
        $this->init_cache();
        $this->init_user();
    }

    function init_db() {
        $this->db = new db(DB_HOST, DB_USER, DB_PW, DB_NAME, DB_CHARSET, DB_CONNECT);
    }

    /* 一旦setting的缓存文件读取失败，则更新所有cache */

    function init_cache() {
        global $setting, $category, $badword;
        $this->cache = new cache($this->db);
        $setting = $this->setting = $this->cache->load('setting');
        #$category = $this->category = $this->cache->load('category');
        #$badword = $this->cache->load('badword', 'find');
        $this->usergroup = $this->cache->load('usergroup', 'groupid');
        #$this->nav = $this->cache->load('nav', 'id', 'displayorder');
    }

    /* 从缓存中读取数据，如果失败，则自动去读取数据然后写入缓存 */

    function fromcache($cachename, $cachetime=3) {
        $cachedata = $this->cache->read($cachename, intval($this->setting['index_life']) * 60); //首页数据缓存，时间为3秒
        if ($cachedata) return $cachedata;
        switch ($cachename) {
            case 'nosolvelist': //待解决问题，网友正在问
                #$this->load('question');
                #$cachedata = $_ENV['question']->list_by_cfield_cvalue_status('', 0, 1, 0, $this->setting['list_indexnosolve']);
                break;
            case 'solvelist'://已解决问题
                #$this->load('question');
                #$cachedata = $_ENV['question']->list_by_cfield_cvalue_status('', 0, 2, 0, $this->setting['list_indexnosolve']);
                break;
        }
        $this->cache->write($cachename, $cachedata);
        return $cachedata;
    }


    function load($model, $base = NULL) {
        $base = $base ? $base : $this;
        if (empty($_ENV[$model])) {
            require APP_ROOT . "/model/$model.class.php";
            eval('$_ENV[$model] = new ' . $model . 'model($base);');
        }
        return $_ENV[$model];
    }

    function init_user() {
        @$sid = tcookie('sid');
        @$auth = tcookie('auth');
        $user = array();
        @list($uid, $password) = empty($auth) ? array(0, 0) : taddslashes(explode("\t", strcode($auth, $this->setting['auth_key'], 'DECODE')), 1);
        if (!$sid) {
            $sid = random(6);
            tcookie('sid', $sid, 31536000);
        }
        if ($uid && $password) {
            $this->load('user');
            $user = $_ENV['user']->get_by_uid($uid);
            ($password != $user['password']) && $user = array();
        }
        if (!$user) {
            $user['uid'] = 0;
            $user['groupid'] = 6;
        } else {
            //$_ENV['user']->refresh_session_time($sid);
            //$user['newmsg'] = $this->db->fetch_total('message', ' touid=' . $uid . '  AND `new`=1 AND `status`!=3  AND `status`!=2');
        }
        $user['sid'] = $sid;
        $user['ip'] = $this->ip;
        $user['loginuser'] = $user['username'];
        //用户头像初始化
       // $user['uid'] && $user['avatar'] = get_avatar_dir($user['uid']);
        $this->user = array_merge($user, $this->usergroup[$user['groupid']]);
    }

    /* 更新用户积分 */

    function credit($uid, $credit1, $credit2=0, $credit3=0, $operation='') {
        if (!$operation)
            $operation = $this->get[0] . '/' . $this->get[1];
        $this->db->query("INSERT INTO " . DB_TABLEPRE . "credit(uid,time,operation,credit1,credit2) VALUES ($uid,{$this->time},'$operation',$credit1,$credit2) ");
        $this->db->query("UPDATE " . DB_TABLEPRE . "user SET credit2=credit2+$credit2,credit1=credit1+$credit1,credit3=credit3+$credit3 WHERE uid=$uid ");
        if (2 == $this->user['grouptype']) {
            $currentcredit1 = $this->user['credit1'] + $credit1;
            $usergroup = $this->db->fetch_first("SELECT g.groupid FROM " . DB_TABLEPRE . "usergroup g WHERE  g.`grouptype`=2  AND $currentcredit1 >= g.creditslower ORDER BY g.creditslower DESC LIMIT 0,1");
            //判断是否需要升级
            if (is_array($usergroup) && ($this->user['groupid'] != $usergroup['groupid'])) {
                $groupid = $usergroup['groupid'];
                $this->db->query("UPDATE " . DB_TABLEPRE . "user SET groupid=$groupid WHERE uid=$uid ");
            }
        }
    }

    /* 权限检测 */

    function checkable($url) {
    	return true;
        $this->regular = $url;
        if (1 == $this->user['groupid'])
            return true;
        $regulars = explode(',', 'user/login,user/logout,user/code,user/getpass,user/resetpass,index/help,js/view,' . $this->user['regulars']);
        return in_array($url, $regulars);
    }

  

    /* 	中转提示页面
      $ishtml=1 表示是跳转到静态网页
     */

    function message($message, $url = '') {
        $seotitle = '操作提示';
        if ('' == $url) {
            $redirect = SITE_URL;
        } else if ('BACK' == $url) {
            $redirect = $url;
        } else {
            $redirect = SITE_URL . $this->setting['seo_prefix'] . $url . $this->setting['seo_suffix'];
        }
        $tpldir = (0 === strpos($this->get[0], 'admin')) ? 'admin' : $this->setting['tpl_dir'];
        include template('tip', $tpldir);
        exit;
    }

    /* 发送通知
      一、操作导致状态改变
      A、当问题被人回答，系统会自动给问题提出者发送通知
      B、当问题被采纳为答案，回答者会收到消息

      二、时间导致状态改变
      A、问题变为关闭状态，给提问者发通知

      三、$type说明:
      0:问题有新回答
      1:回答被采纳
      2:问题超时自动关闭
      3:回答有新评分
     */

    function send($uid, $qid, $type, $aid=0) {
        $question = $this->db->fetch_first("SELECT * FROM " . DB_TABLEPRE . "question WHERE id='$qid'");
        $msgtpl = unserialize($this->setting['msgtpl']);
        //消息模板
        $message = array();
        foreach ($msgtpl[$type] as $msg => $val) {
            $message[$msg] = str_replace('{wtbt}', $question['title'], $val);
            $message[$msg] = str_replace('{wtms}', $question['description'], $message[$msg]);
            $message[$msg] = str_replace('{wzmc}', $this->setting['site_name'], $message[$msg]);
            if ($aid) {
                $answer = $this->db->fetch_first("SELECT * FROM " . DB_TABLEPRE . "answer WHERE id=$aid");
                $message[$msg] = str_replace('{hdnr}', $answer['content'], $message[$msg]);
            }
        }

        $message['content'] .='<br /> <a href="' . url('question/view/' . $qid, 1) . '">点击查看问题</a>';
        $time = $this->time;
        $msgfrom = $this->setting['site_name'] . '管理员';
        $touser = $this->db->fetch_first("SELECT * FROM " . DB_TABLEPRE . "user WHERE uid=" . $uid);
        //1,3,5,7 允许站内消息
        if ((1 & $touser['isnotify']) && $this->setting['notify_message']) {
            $this->db->query('INSERT INTO ' . DB_TABLEPRE . "message  SET `from`='" . $msgfrom . "' , `fromuid`=0 , `touid`=$uid  , `subject`='" . $message['title'] . "' , `time`=" . $time . " , `content`='" . $message['content'] . "'");
        }
        //2,3,6,7 允许发邮件
        if ((2 & $touser['isnotify']) && $this->setting['notify_mail']) {
            sendmail($touser, $message['title'], $message['content']);
        }
        //4,5,6,7 允许发手机短信
    }

    /* 生成一个问题的静态页面 */

    function write_question($question) {
        global $setting, $db;
        include_once APP_ROOT . '/control/question.php';
        $this->get[2] = $question['id'];
        $control = new questioncontrol($this->get, $this->post);
        ob_start();
        $control->onview();
        $html = ob_get_contents();
        ob_end_clean();
        $staticurl = getstaticurl($question);
        if ($question['url'] && file_exists($question['url'])) {
            unlink($question['url']);
        }
        $this->db->query("UPDATE `" . DB_TABLEPRE . "question`  SET url='$staticurl'  WHERE id =" . $question['id']);
        forcemkdir(dirname($staticurl));
        writetofile($staticurl, $html);
        return $staticurl;
    }

    /* 检查验证码 */

    function checkcode() {
        $this->load('user');
        if (strtolower(trim($this->post['code'])) != $_ENV['user']->get_code()) {
            $this->message("验证码错误!", 'BACK');
        }
    }

}

?>
